/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvneng.core;

import com.alibaba.fastjson.JSON;
import com.github.zengfr.easymodbus4j.ModbusConfs;
import com.github.zengfr.easymodbus4j.ModbusConsts;
import com.github.zengfr.easymodbus4j.common.util.ParseStringUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 输入运行参数如：4,127.0.0.1,502,1,0,T,0,T,12000,heartbeat,0,54321,2000,100,F,F,T,F,127.0.0.1:502:1:1;127.0.0.1:502:2:2
 * 从左至右分别表示：type,host,port,unit_IDENTIFIER,transactionIdentifierOffset,showDebugLog,idleTimeout,autoSend,sleep,heartbeat,ignoreLengthThreshold,udpPort,maximumAddress,batchQuantity,coils,discreteInputs,holdingRegisters,inputRegisters,slaveList
 * 具体用法见类：ModbusConsoleApp.java
 *
 * @author zengfr QQ:362505707/1163551688 Email:zengfr3000@qq.com
 *         https://github.com/zengfr/easymodbus4j *
 */
public class ModbusConfig {
	private static final InternalLogger logger = InternalLoggerFactory.getInstance(ModbusConfig.class);
	public int type;
	public String host;
	public int port;
	public boolean showDebugLog;
	public boolean autoSend;
	public int idleTimeOut;
	public int sleep;

	public short unit_IDENTIFIER;
	public short transactionIdentifierOffset;
	public int ignoreLengthThreshold;
	public String heartbeat;
	public int scheduleFixedDelay;
	public int udpPort;
	public int maximumAddressLen;//最大地址数量，就是最多 多少个点位地址
	public int batchQuantity;//每次去点表获取的最大数量（分批获取所有点表地址，batchQuantity要求 < maximumAddressLen）
	public boolean coils;
	public boolean discreteInputs;
	public boolean holdingRegisters;
	public boolean inputRegisters;
	public static Map<Integer,IpAddress> slaveMap = new HashMap<>();

	/**
	 *
	 * @param argsArray 4,127.0.0.1,502,1,0,T,0,T,12000,heartbeat,0,54321,2000,100,F,F,T,F,127.0.0.1:502:1:1;127.0.0.1:502:2:2
	 *                  type,host,port,unit_IDENTIFIER,transactionIdentifierOffset,showDebugLog,idleTimeout,autoSend,sleep,heartbeat,ignoreLengthThreshold,udpPort,maximumAddressLen,batchQuantity,coils,discreteInputs,holdingRegisters,inputRegisters,slaveList
	 * @return
	 */
	public static ModbusConfig parse(String[] argsArray) {
		ModbusConfig cfg = new ModbusConfig();

		cfg.type = ParseStringUtil.parseInt(argsArray, 0, 0);
		cfg.host = ParseStringUtil.parseString(argsArray, 1, ModbusConsts.DEFAULT_HOTST_IP);
		cfg.port = ParseStringUtil.parseInt(argsArray, 2, ModbusConfs.DEFAULT_MODBUS_PORT);
		cfg.unit_IDENTIFIER = ParseStringUtil.parseShort(argsArray, 3, ModbusConsts.DEFAULT_UNIT_IDENTIFIER);
		cfg.transactionIdentifierOffset = ParseStringUtil.parseShort(argsArray, 4, (short) 0);
		cfg.showDebugLog = ParseStringUtil.parseBoolean(argsArray, 5, true);
		cfg.idleTimeOut = ParseStringUtil.parseInt(argsArray, 6, ModbusConfs.IDLE_TIMEOUT_SECOND);

		cfg.autoSend = ParseStringUtil.parseBoolean(argsArray, 7, true);
		cfg.sleep = ParseStringUtil.parseInt(argsArray, 8, 1000 * 15);
		cfg.heartbeat = ParseStringUtil.parseString(argsArray, 9, ModbusConsts.HEARTBEAT);
		cfg.ignoreLengthThreshold = ParseStringUtil.parseInt(argsArray, 10, ModbusConfs.RESPONS_EFRAME_IGNORE_LENGTH_THRESHOLD);
		
		cfg.udpPort = ParseStringUtil.parseInt(argsArray, 11, ModbusConfs.DEFAULT_MODBUS_PORT5);
		cfg.maximumAddressLen = ParseStringUtil.parseInt(argsArray, 12, 2000);
		cfg.batchQuantity = ParseStringUtil.parseInt(argsArray, 13, 100);

		cfg.coils = ParseStringUtil.parseBoolean(argsArray, 14, false);
		cfg.discreteInputs = ParseStringUtil.parseBoolean(argsArray, 15, false);
		cfg.holdingRegisters = ParseStringUtil.parseBoolean(argsArray, 16, true);
		cfg.inputRegisters = ParseStringUtil.parseBoolean(argsArray, 17, false);

		String slaveList = ParseStringUtil.parseString(argsArray, 18, "");//127.0.0.1:502:1:1;127.0.0.1:502:2:2
		String[] array = null;
		if(!"".equals(slaveList)){
			if(slaveList.contains(";")){
				array = slaveList.split(";");
			}else{
				array = new String[1];
				array[0] = slaveList;
			}
		}
		if(array != null && array.length > 0){
			for(String item : array){
				if(item != null && !"".equals(item) && item.contains(":")){
					String[] itemArray = item.split(":");
					String host = itemArray[0];
					String port = itemArray[1];
					String slaveId = itemArray[2];
					String tempSlaveId = itemArray[3];//对外公布的slaveId
					String maximumAddressLen = itemArray[4];//本端口最大modbus地址数量
					IpAddress ipAddress = new IpAddress();
					ipAddress.setHost(host);
					ipAddress.setPort(Integer.parseInt(port));
					ipAddress.setSlaveId(Integer.parseInt(slaveId));
					ipAddress.setMaximumAddressLen(Integer.parseInt(maximumAddressLen));
					slaveMap.put(Integer.parseInt(tempSlaveId),ipAddress);
				}
			}
		}
		logger.info(JSON.toJSONString(cfg));
		return cfg;
	}
}
